import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
import matplotlib.pyplot as plt

# 1. 数据准备（示例数据）

sales = [1977,146,63,39,38,33,33,44,42,29,33,28,50,23,16,44,19,15,13,20,16,12,13,22,18,19,19,12,22,20]
# dates = pd.date_range(start='2023-01-01', periods=100)
dates = pd.date_range(start='2025-01-10', periods=len(sales), freq='D')
# 模拟销量递增趋势
df = pd.DataFrame({'Date': dates, 'Sales': sales})

# 2. 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df[['Sales']])

# 3. 创建时间窗口数据集
def create_dataset(data, time_steps=1):
    X, y = [], []
    for i in range(len(data) - time_steps):
        X.append(data[i:(i + time_steps), 0])
        y.append(data[i + time_steps, 0])
    return np.array(X), np.array(y)

time_steps = 7  # 用前7天预测第8天
X, y = create_dataset(scaled_data, time_steps)

# 4. 划分训练/测试集
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]

# 5. 调整LSTM输入格式 [样本数, 时间步长, 特征数]
X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)

# 6. 构建LSTM模型
model = Sequential()
model.add(LSTM(50, activation='relu', input_shape=(time_steps, 1)))
model.add(Dense(1))
model.compile(optimizer='adam', loss='mse')

# 7. 训练模型
history = model.fit(
    X_train, y_train,
    epochs=100,
    batch_size=16,
    validation_split=0.2,
    verbose=0
)

# 8. 预测未来14天
last_sequence = scaled_data[-time_steps:]  # 取最新14天数据
future_days = 14
predictions = []

for _ in range(future_days):
    input_seq = last_sequence.reshape((1, time_steps, 1))
    pred = model.predict(input_seq, verbose=0)
    predictions.append(pred[0, 0])
    # 更新序列：移除最早数据，添加新预测
    last_sequence = np.append(last_sequence[1:], pred)

# 9. 反归一化
true_predictions = scaler.inverse_transform(np.array(predictions).reshape(-1, 1))

print(true_predictions)

# 10. 结果可视化
plt.figure(figsize=(12, 6))
plt.plot(df['Date'], df['Sales'], label='Historical Sales')
future_dates = pd.date_range(start=df['Date'].iloc[-1] + pd.Timedelta(days=1), periods=future_days)
plt.plot(future_dates, true_predictions, 'ro--', label='Predicted Sales')
plt.title('LSTM Sales Prediction')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.legend()
plt.grid(True)
plt.show()